<template>
  <div class="body-box">
    <div id="mapContainer"></div>
    <div class="search-map">
      <el-form :inline="true">
        <el-form-item>
          <el-select v-model="province" @change="changeProvince($event,1)">
          <el-option
            v-for="(item,key) in province_arr"
            :key="key"
            :value="item.name"
            :label="item.name"
          ></el-option>
        </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="city" @change="changeCity">
          <el-option
            v-for="(item,key) in city_arr"
            :key="key"
            :value="item.name"
            :label="item.name"
          ></el-option>
        </el-select>
        </el-form-item>
        <!-- <div class="now-select-map">当前选择：{{local}}</div> -->
        <el-form-item>
          <el-input
            id="keyword"
            name="keyword"
            placeholder="请输入关键字：(选定后搜索)"
            v-model="addr_location"
          ></el-input>
        </el-form-item>
      </el-form>
      <div class="btn-box-am">
        <el-button class="com-btn" icon="el-icon-check" @click="trueAddr()">确定选择</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import AMap from "AMap"; // 引入高德地图

export default {
  data() {
    return {
      longitude: "",
      latitude: "",
      local: "请选择定位地址",
      province: "",
      city: "",
      area: "",
      province_arr: [],
      city_arr: [],
      addr_location: "",
      city_adcode : '',
    };
  },
  mounted() {
    var that = this;
    AMap.plugin(
      [
        "AMap.Geolocation",
        "AMap.Autocomplete",
        "AMap.PlaceSearch",
        "'AMap.DistrictSearch"
      ],
      function() {
        //获取行政区
        var districtSearch = new AMap.DistrictSearch({
          // 关键字对应的行政区级别，country表示国家
          level: "country",
          //  显示下级行政区级数，1表示返回下一级行政区
          subdistrict: 2
        });

        // 搜索所有省/直辖市信息
        districtSearch.search("中国", function(status, result) {
          that.province_arr = result.districtList[0].districtList;
          console.log(that.province_arr);
          // 查询成功时，result即为对应的行政区信息
        });

        let geolocation = new AMap.Geolocation({
          // 是否使用高精度定位，默认：true
          enableHighAccuracy: true,
          // 设置定位超时时间，默认：无穷大
          timeout: 10000
        });

        geolocation.getCurrentPosition();
        AMap.event.addListener(geolocation, "complete", onComplete);
        AMap.event.addListener(geolocation, "error", onError);

        function onComplete(data) {
          // data是具体的定位信息
          let map = new AMap.Map("mapContainer", {
            center: [data.position.lng, data.position.lat],
            resizeEnable: true,
            zoom: 12,
            keyboardEnable: false
          });
          // 地理编码
          var geocoder = new AMap.Geocoder({
            // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
          });
          map.on("click", function(e) {
            that.longitude = e.lnglat.lng;
            that.latitude = e.lnglat.lat;
            var lnglat = [e.lnglat.lng, e.lnglat.lat];
            geocoder.getAddress(lnglat, function(status, result) {
              if (status === "complete" && result.info === "OK") {
                // result为对应的地理位置详细信息
                that.local = result.regeocode.formattedAddress;
                that.addr_location = result.regeocode.formattedAddress;
                // result为对应的地理位置详细信息
                that.province = result.regeocode.addressComponent.province;
                that.city = result.regeocode.addressComponent.city;
                console.log(result);
                // that.province = result.regeocode.addressComponent.province;
                // that.city = result.regeocode.addressComponent.city;
                // that.area = result.regeocode.addressComponent.district;
              }
            });
          });
          var autoOptions = {
            city: that.city_adcode, //城市，默认全国
            input: "keyword", //使用联想输入的input的id,
            citylimit:true
          };
          var autocomplete = new AMap.Autocomplete(autoOptions);
          var placeSearch = new AMap.PlaceSearch({
            city: that.city,
            map: map,
            citylimit: true
          });
          AMap.event.addListener(autocomplete, "select", function(e) {
            var data = e.poi.location;
            that.longitude = data.lng;
            that.latitude = data.lat;
            that.local = e.poi.district + e.poi.address + "-" + e.poi.name;
            var pca = e.poi.district;
            var pca_arr = pca.split("省");
            if (pca_arr.length > 1) {
              that.province = pca_arr[0] + "省";
              var pca_arr = pca_arr[1].split("市");
              that.city = pca_arr[0] + "市";
            } else {
              var pca_arr = pca.split("市");
              that.city = pca_arr[0] + "市";
              that.province = pca_arr[0];
            }
            that.addr_location = e.poi.name;
            // placeSearch.setCity(e.poi.adcode);
            //console.log(e.poi.name);
            //placeSearch.search(e.poi.name);
            that.changeProvince(that.province, 2);
          });
        }

        function onError(data) {
          // 定位出错
          this.toast(0, "定位失败");
        }
      }
    );
  },
  methods: {
    //选择省
    changeProvince(e, param) {
      if (param != 2) {
        this.city = "";
        this.addr_location = '';
      }
      this.city_arr = [];
      var adcode = "";
      for (var i in this.province_arr) {
        if (this.province_arr[i].name == e) {
          adcode = this.province_arr[i].adcode;
          this.city_arr = this.province_arr[i].districtList;
        }
      }
      // if(param == 2) return false;
      var addr = this.province + this.city + this.addr_location;
      AMap.plugin(["AMap.Geocoder", "AMap.PlaceSearch"], function() {
        var geocoder = new AMap.Geocoder({
          // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
          city: adcode
        });

        geocoder.getLocation(addr, function(status, result) {
          if (status === "complete" && result.info === "OK") {
            console.log(result);
            // result中对应详细地理坐标信息
            let map = new AMap.Map("mapContainer", {
              center: [
                result.geocodes[0].location.lng,
                result.geocodes[0].location.lat
              ],
              resizeEnable: true,
              zoom: 12,
              keyboardEnable: false
            });
          }
        });
      });
    },
    //选择市
    changeCity(e) {
      var adcode = "";
      for (var i in this.city_arr) {
        if (this.city_arr[i].name == e) {
          adcode = this.city_arr[i].adcode;
        }
      }
      this.city_adcode = adcode;
      var addr = this.province + this.city;
      AMap.plugin("AMap.Geocoder", function() {
        var geocoder = new AMap.Geocoder({
          // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
          city: adcode
        });

        geocoder.getLocation(addr, function(status, result) {
          if (status === "complete" && result.info === "OK") {
            console.log(result);
            // result中对应详细地理坐标信息
            let map = new AMap.Map("mapContainer", {
              center: [
                result.geocodes[0].location.lng,
                result.geocodes[0].location.lat
              ],
              resizeEnable: true,
              zoom: 12,
              keyboardEnable: false
            });
          }
        });
      });
    },
    trueAddr() {
      if (!this.local || !this.latitude || !this.longitude || !this.province || !this.city)
        return this.toast(0, "请先定位选择地址");
      this.$parent.form.address = this.local;
      this.$parent.form.longitude = this.longitude;
      this.$parent.form.latitude = this.latitude;
      this.$parent.form.province = this.province;
      this.$parent.form.city = this.city;
      this.$parent.$layer.closeAll();
    }
  }
};
</script>

<style>
.search-map {
  position: fixed;
  top: 50px;
  width: 760px;
  left: 20px;
  height: 32px;
  line-height: 32px;
}
.now-select-map {
  height: 32px;
  background: #fff;
  overflow: hidden;
  padding: 0 10px;
  float: left;
  box-shadow: 1px 1px 3px rgba(26, 26, 26, 0.3);
}
/* .map-select-input {
  float: right;
  height: 32px;
  width: 200px;
} */
.map-select-input > input {
  width: 100%;
  height: 32px;
  border: 1px solid #ccc;
  border-radius: 3px;
  text-indent: 1em;
  box-shadow: 1px 1px 3px rgba(26, 26, 26, 0.3);
}
.map-select-input > input:focus {
  outline: none;
}
.btn-box-am {
  position: fixed;
  bottom: 20px;
  text-align: right;
  width: 760px;
  z-index: 99;
}
</style>